package com.anjufang.controller;

import com.anjufang.entity.SourceUser;
import com.anjufang.service.user.UserExcelService;
import com.anjufang.utils.Result;
import com.anjufang.utils.StringUtils;
import com.anjufang.utils.cache.CacheKey;
import com.anjufang.utils.cache.RedisGroups;
import com.anjufang.utils.cache.RedisUtil;
import com.anjufang.utils.constant.Constant;
import com.anjufang.utils.excel.ExcelImport;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("user/excel")
public class UserExcelController extends BaseController {

    @Autowired
    private UserExcelService userExcelService;

    @PostMapping("import")
    public Result importExcel(HttpServletRequest request) {

        ExcelImport excelImport = new ExcelImport();
        try {
            List<Object[]> dataList = excelImport.importExcel(request);
            if (dataList == null || dataList.size() == 0) {
                return Result.error("excel内容为空,导入失败!");
            }
            String msg = userExcelService.importExcel(dataList);
            if (StringUtils.isNotBlank(msg)) {
                return Result.error("以下数据重复：" + msg);
            }
            //createUserNoCache(dataList.size());
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入失败，请检查数据是否正确");
        }
    }

    private void createUserNoCache(int size) {

        List<Integer> numList = new ArrayList<>();
        for (int i = 1; i <= size; i++) {
            numList.add(i);
        }
        // 打乱数据
        Collections.shuffle(numList);
        // 先清除旧缓存
        CacheKey key = new CacheKey(RedisGroups.CACHE_USER_NO_KEY);
        RedisUtil.delete(key);
        for(Integer i : numList) {
            RedisUtil.lpush(key, i);
        }
    }

}
